<template>
  <view class="page over_hidden">
    <!-- #ifdef APP-PLUS || H5 -->
    <view :id="option.id"
          :option="option"
          :treeDom="treeDom"
          :change:treeDom="treeGraph.changeTreeGraphSize"
          :change:option="treeGraph.changeTreeGraphData"
          style="width: 100%;height: 100%;over"></view>
    <!-- #endif -->
    <!-- #ifndef APP-PLUS || H5 -->
    <view>非 APP、H5 环境不支持</view>
    <!-- #endif -->
  </view>
</template>

<script>
import treeData from "./data3";
export default {
  data() {
    return {
      option: {
        id: "canvasId",
        data: treeData,
      },
      treeDom: {
        width: 375,
        height: 500,
      },
    };
  },
  mounted() {
    uni
      .createSelectorQuery()
      .select("#canvasId")
      .boundingClientRect((data) => {
        this.treeDom = data;
      })
      .exec();
  },
  methods: {},
};
</script>

<script module="treeGraph" lang="renderjs">
import F6 from '@/static/js/F6/f6.min.js'
import TreeGraph from '@/static/js/F6/extends/graph/treeGraph.js'
F6.registerGraph('TreeGraph', TreeGraph)

export default {
  data() {
    return {
      graph: null,  
    }
  },  
  mounted() {
    // if (typeof window.F6 === 'function') {
      this.init()
    // } else {
    	// 动态引入较大类库避免影响页面展示
    	// const script = document.createElement('script')
    	// view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
    	// script.src = 'https://gw.alipayobjects.com/os/antv/pkg/_antv.f6-{$version}/dist/f6.js'
    	// script.onload = this.init.bind(this)
    	// document.head.appendChild(script)
    // }
  },
  methods: {
    init() {
      console.log('init') 

      // registerNode
      F6.registerNode('file-node', {
        draw: function draw(cfg, group) {
          const keyShape = group.addShape('rect', {
            attrs: {
              x: 10,
              y: -12,
              fill: '#fff',
              stroke: null,
            },
          });
          let isLeaf = false;
          if (cfg.collapsed) {
            group.addShape('marker', {
              attrs: {
                symbol: 'triangle',
                x: 4,
                y: -2,
                r: 4,
                fill: '#666',
              },
              name: 'marker-shape',
            });
          } else if (cfg.children && cfg.children.length > 0) {
            group.addShape('marker', {
              attrs: {
                symbol: 'triangle-down',
                x: 4,
                y: -2,
                r: 4,
                fill: '#666',
              },
              name: 'marker-shape',
            });
          } else {
            isLeaf = true;
          }
          const shape = group.addShape('text', {
            attrs: {
              x: 15,
              y: 4,
              text: cfg.name,
              fill: '#666',
              fontSize: 16,
              textAlign: 'left',
              fontFamily:
                typeof window !== 'undefined'
                  ? window.getComputedStyle(document.body, null).getPropertyValue('font-family') ||
                    'Arial, sans-serif'
                  : 'Arial, sans-serif',
            },
            name: 'text-shape',
          });
          const bbox = shape.getBBox();
          let backRectW = bbox.width;
          let backRectX = keyShape.attr('x');
          if (!isLeaf) {
            backRectW += 8;
            backRectX -= 15;
          }
          keyShape.attr({
            width: backRectW,
            height: bbox.height + 4,
            x: backRectX,
          });
          return keyShape;
        },
      });

      // registerEdge
      F6.registerEdge( 'step-line',
        {
          getControlPoints: function getControlPoints(cfg) {
            const { startPoint } = cfg;
            const { endPoint } = cfg;
            return [
              startPoint,
              {
                x: startPoint.x,
                y: endPoint.y,
              },
              endPoint,
            ];
          },
        }, 'polyline');

      this.graph = new F6.TreeGraph({
        container: this.option.id,
        width: this.treeDom.width,
        height: this.treeDom.height,
        animate: true,
        fitView: true, // 画布自适应
        fitCenter: true, //图将会被平移，图的中心将对齐到画布中心，但不缩放。优先级低于 fitView。
        linkCenter: true, //指定边是否连入节点的中心
        modes: {
          default: ['drag-canvas', 'zoom-canvas',
          {
              type: 'collapse-expand',
              onChange: function onChange(item, collapsed) {
                const model = item.getModel();
                model.collapsed = collapsed;
                return true;
              },
            },
          ]
        },
        defaultNode: {
          size: 26,
          anchorPoints: [
            [0, 0.5],
            [1, 0.5],
          ],
        },
        defaultEdge: {
          style: {
            stroke: '#A3B1BF',
          },
        },
        layout: {
          type: 'indented',
          isHorizontal: true,
          direction: 'LR',
          indent: 30,
          getHeight: function getHeight() {
            return 16;
          },
          getWidth: function getWidth() {
            return 16;
          },
        },
      }) 

      let centerX = 0;
      this.graph.node(function(node) {
        if (node.id === 'Modeling Methods') {
          centerX = node.x;
        }

        // position的取值（由于ESlint禁止嵌套的三元表达，所以单独提取出来写）
        let position_value = null;
        if (node.children && node.children.length > 0) {
          position_value = 'left';
        } else if (node.x > centerX) position_value = 'right';
        else position_value = 'left';

        return {
          label: node.id,
          labelCfg: {
            offset: 5,
            position: position_value,
          },
        };
      });

      this.graph.node((node) => {
        return {
          type: 'file-node',
          label: node.name,
        };
      });

      this.graph.edge(() => {
        return {
          type: 'step-line',
        };
      }); 
      this.graph.data(this.option.data);
      this.graph.render(); 
    },
    changeTreeGraphSize() { 
      this.graph.changeSize(this.treeDom.width, this.treeDom.height)
      this.graph.render(); 
      this.graph.fitView()
    },
    changeTreeGraphData() {
      this.graph.changeData(this.option.data)
      this.graph.fitView()
    }
  }
}
</script>
